package com.LeeCode;

/**
 * 统计完全子数组的数目
 */

import java.util.HashMap;
import java.util.HashSet;

public class Code2799 {
    public static void main(String[] args) {
        int[] nums = {5, 5, 5, 5};
        System.out.println(new Code2799().countCompleteSubarrays(nums));

    }

    public int countCompleteSubarrays(int[] nums) {
        int ans = 0;
        HashSet<Integer> set = new HashSet<>();

        for (int num : nums) {
            set.add(num);
        }

        HashMap<Integer, Integer> window = new HashMap<>();
        int left = 0, right = 0, count = 0;

        for (left = 0; left < nums.length; left++) {
            while (count < set.size() && right < nums.length) {
                window.put(nums[right], window.getOrDefault(nums[right], 0) + 1);
                if (window.get(nums[right]) == 1) { // 遇到了新元素
                    count++;
                }
                right++;
            }

            if (count >= set.size()) {
                ans += nums.length - right + 1;
            }

            window.put(nums[left], window.getOrDefault(nums[left], 0) - 1);
            if (window.get(nums[left]) == 0) {
                count--;
            }
        }

        return ans;
    }
}
